<?

//require_once('../config.inc.php');
require_once($config['app_dir'] . '/includes/template.class.php');
require_once($config['app_dir'] . '/includes/db.class.php');


class objTimezone {
	var $citiesData = array();
	var $currHour,$currMin,$currSec,$currMon,$currDay,$currYear;

	var $city_data = array(
	array('New York',-300,1),
	array('London',0,1),
	array('Barcelona',60,1),
	array('Tokyo',540,1),
	array('Sydney',660,1)
	);



 		function __construct() {
           	$this->setCurrentTime();
           	$this->_DataBase = objDataBase::GetInstance();
            $this->_sqls();
      	} //constructor


      	function setCurrentTime() {
	      	$this->currHour = date("G");
			$this->currMin = date("i");
			$this->currSec = date("s");
			$this->currMon = date("m");
			$this->currDay = date("d");
			$this->currYear = date("Y");
        }

        function parseCurrentTime() {
	      	$timeString = date("D, M j Y, G:i:s", mktime($this->currHour, $this->currMin, $this->currSec, $this->currMon, $this->currDay, $this->currYear))." GMT";
	      	return $timeString;
        }

       function parseCities() {
       		$cityRows = "";
       		foreach($this->city_data as $city){
       			$cityTime = date("G:i", mktime($this->currHour, $this->currMin + $city[1], $this->currSec, $this->currMon, $this->currDay, $this->currYear));
       			$citiesData[] = array($city[0],$cityTime);
       		}
           return $citiesData;
       } //parseCities


       function Render() {
      		$timeZ = new objTemplate();
            return $Calc->Fetch('texts/_time.tpl');
      	}



      // get all timezones array
      public function TZDisplayArr() {      		$timezones = array();
	    	$rs = $this->_DataBase->handler->Execute($this->_querys['get_timezones']);
	     	$cnter=0;
	      	while (!$rs->EOF) {
	            $timezones[$cnter]['id'] = $rs->fields['ID'];
             	$timezones[$cnter]['descr'] = $rs->fields['Description'];
             	$timezones[$cnter]['oSum'] = $rs->fields['OffsetSummer'];
             	$timezones[$cnter]['oWin'] = $rs->fields['OffsetWinter'];
              	$timezones[$cnter]['offsetMin'] = $rs->fields['OffsetSummer'] + $rs->fields['OffsetWinter'];

              	// format offset in HH:MM format (offsetHrs)
                $timezones[$cnter]['offsetMin']<0 ? $mins = -1 * $timezones[$cnter]['offsetMin'] : $mins = $timezones[$cnter]['offsetMin'];
               	($mins%60)==0 ? $mins="00" : $mins = $mins%60;
                $timezones[$cnter]['offsetHrs'] = intval($timezones[$cnter]['offsetMin']/60).":".$mins;

                $cnter++;
		      	$rs->MoveNext();
			}
			return $timezones;
		}

        // if Summer return 1, if Winter return 0
        public function getDaylightSaving($tzID=false) {        	if (!$tzID) $tzID=28; // set GMT as default timezone        	try{
	           $rs = $this->_DataBase->handler->Execute($this->_querys['get_timezone_period'],array($tzID));
	         } catch(exception $e) {
	         	//$this->_db->debug = true;
	            if (true == $this->_db->debug ) {
	              adodb_pr($e);
	              $e = adodb_backtrace($e->trace);
	            }
	            die('DB Error: '.$e->sql);
	         }
			$weekStart = $rs->fields['WeekStart']; //default 13th week
			$weekEnd = $rs->fields['WeekEnd']; //default 42th week
			$week = intval(date("W"));

			if ($week>$weekStart && $week<$weekEnd) return 0;
			else return 1;
      } //getDaylightSaving



        public function getUserTimezone($userID) {

		try{
           $rs = $this->_DataBase->handler->Execute($this->_querys['get_user_timezone'],array($userID));
         } catch(exception $e) {         	//$this->_db->debug = true;
            if (true == $this->_db->debug ) {
              adodb_pr($e);
              $e = adodb_backtrace($e->trace);
            }
            die('DB Error: '.$e->sql);
         }

		$isWinter = $this->getDaylightSaving($rs->fields['Timezone']); //check is winter


		//if summer now than do not count winter offset (multiply it by 0)
         $this->secondsOffset = $rs->fields['OffsetSummer'] + $rs->fields['OffsetWinter'] * $isWinter;
         $this->timeZoneName = $rs->fields['Description'];
         $this->timeZoneID = $rs->fields['Timezone'];


         return $this->timeZoneID;

      } //getUserTimezone


      public function getOffsetByTimezoneId($tzID) {
		try{
           $rs = $this->_DataBase->handler->Execute($this->_querys['get_offset_timezone'],array($tzID));
         } catch(exception $e) {
         	//$this->_db->debug = true;
            if (true == $this->_db->debug ) {
              adodb_pr($e);
              $e = adodb_backtrace($e->trace);
            }
            die('DB Error: '.$e->sql);
         }

         $isWinter = $this->getDaylightSaving($tzID); //check is winter
         echo $isWinter;

		//if summer now than do not count winter offset (multiply it by 0)
         $this->tzAbbreviation = $rs->fields['Abbreviation'];
         $resultOffset = ($rs->fields['OffsetSummer'] + $rs->fields['OffsetWinter'] * $isWinter)*60; // convert offset from minutes to seconds
         return $resultOffset;
      } //getOffsetByTimezoneId


      public function getOffsetByUserId($uID) {
		try{
           $rs = $this->_DataBase->handler->Execute($this->_querys['get_offset_user'],array($uID));
         } catch(exception $e) {
         	//$this->_db->debug = true;
            if (true == $this->_db->debug ) {
              adodb_pr($e);
              $e = adodb_backtrace($e->trace);
            }
            die('DB Error: '.$e->sql);
         }

         $isWinter = $this->getDaylightSaving($rs->fields['Timezone']); //check is winter
  		echo $isWinter;
		//if summer now than do not count winter offset (multiply it by 0)
         $this->tzAbbreviation = $rs->fields['Abbreviation'];
         $resultOffset = ($rs->fields['OffsetSummer'] + $rs->fields['OffsetWinter'] * $isWinter)*60; // convert offset from minutes to seconds
         return $resultOffset;
      } //getOffsetByTimezoneId


      protected function _sqls() {
            $this->_querys['get_timezones'] = 'select * from fa_timezones where Active=1 order by (OffsetSummer+OffsetWinter)';
            $this->_querys['get_user_timezone'] = 'SELECT u.UserID, u.Timezone, t.OffsetSummer, t.OffsetWinter, t.Description FROM fa_users u LEFT JOIN fa_timezones t ON u.TimeZone=t.ID WHERE u.UserID=?';
            $this->_querys['get_offset_user'] = 'SELECT u.Timezone, t.OffsetSummer, t.OffsetWinter, t.Abbreviation FROM fa_users u LEFT JOIN fa_timezones t ON u.TimeZone=t.ID WHERE u.UserID=?';
            $this->_querys['get_offset_timezone'] = 'SELECT OffsetSummer, OffsetWinter, Abbreviation FROM fa_timezones WHERE ID=?';
            $this->_querys['get_timezone_period'] = 'SELECT WeekStart, WeekEnd FROM fa_timezones WHERE ID=?';
      } //_sqls


} // Timezone

    function showTimeZones() {

         $tabContent = '';

         $timeZ = new objTimezone();


         $cTemplate = new objTemplate();
    	 //$cTemplate->Assign('zones',$timeZ->graphArrDetailed);
    	 $cTemplate->Assign('currTime',$timeZ->parseCurrentTime());
    	 $cTemplate->Assign('data',$timeZ->parseCities());

         $tabContent .= $cTemplate->Fetch('texts/_time_content.tpl');
         //----------------------------------------------------------------------
         $objResponse = new xajaxResponse();
		 $objResponse->addAssign("time_content","innerHTML", $tabContent);

         //----------------------------------------------------------------------

         return $objResponse;
    }//getCalcResult



?>